/* eslint-disable array-callback-return */
/* eslint-disable consistent-return */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined, LinkOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, Input, Select, Tooltip, message, Spin } from 'antd';
import queryString from 'query-string';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import Policy from '../../components/PolicyDetail';
import Area from '../../components/Area';
import BankForm from './Bank';

const { Option } = Select;
const FormItem = Form.Item;
@connect(({ singlemanage, loading }) => ({
  singlemanage,
  loading: loading.models.singlemanage,
  formFieldsValue: singlemanage.formFieldsValue,
  expandForm: singlemanage.expandForm,
  pageData: singlemanage.pageData,
  activeKey: singlemanage.activeKey,
  accuUpdateData: singlemanage.accuUpdateData, // 公积金要回显的数据
}))
@Form.create()
class AdvancedForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '', // 页签
      custAccuAccoId: '', // 公积金账户id
      updateModVisible: 'false', // 银行弹框变量
      custId: '', // 客户名称id
      payWayList: [], // 支付方式
      payWay: '3',
      selectedAreaId: '', // 选中的地区id
      fundList: [],
      bankAccoList: [], // 下拉列表中客户银行账户信息
      bankList: [], // 银行列表
      PAY_FEES_WAY: [],
      yesNoList: [],
      corpProp: '', // 公积金企业缴纳比例
      empProp: '', // 公积金个人缴纳比例
      policyVisible: 'false',
      plcyId: '', // 公积金组合id
      accuOrIns: '2', // 社保传1 ， 公积金传2
      isdoneFlag: '1', // 是否开户完成
      exceedCeilingFlag: '2', // 是否可突破上线
      submitting: false,
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    this.state.activeKey = queryString.parse(location.search).activeKey;
    const custAccuAccoId = queryString.parse(location.search).baseInfoId;
    this.setState({ custAccuAccoId });
    // 获取页面所有的字典数据
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['ACCO_PAY_WAY', 'BANK_ID', 'PAY_FEES_WAY', 'YES_NO_FLAG'],
    }).then(data => {
      if (data && data.ACCO_PAY_WAY && data.ACCO_PAY_WAY.length) {
        this.setState({ payWayList: data.ACCO_PAY_WAY });
      }
      if (data && data.BANK_ID && data.BANK_ID.length) {
        this.setState({ bankList: data.BANK_ID });
      }
      if (data && data.YES_NO_FLAG && data.YES_NO_FLAG.length) {
        this.setState({ yesNoList: data.YES_NO_FLAG });
      }
      if (data && data.PAY_FEES_WAY && data.PAY_FEES_WAY.length) {
        data.PAY_FEES_WAY.forEach(item => {
          if (item.itemName === '单立户') {
            this.setState({ payWay: item.itemCode });
          }
        });
        this.setState({ PAY_FEES_WAY: data.PAY_FEES_WAY });
      }
    });
    // 查公积金的回显数据
    dispatch({
      type: 'singlemanage/getAccuDetail',
      payload: {
        custAccuAccoId,
      },
    }).then(res => {
      if (res.success && res.data) {
        // 根据客户名称id，获取银行账户信息列表
        if (res.data.custId) {
          this.setState({ custId: res.data.custId });
          this.getBankList(res.data.custId);
        }
        // 获取公积金组合
        if (res.data.payWay && res.data.areaId) {
          this.setState({ plcyId: res.data.plcyId });
          const areaId = res.data.areaId.split(',');
          this.getAreaData(false, areaId[areaId.length - 1]);
        }
        // 是否可突破上线
        if (res.data.exceedCeilingFlag) {
          this.setState({ exceedCeilingFlag: res.data.exceedCeilingFlag });
        }
        return res.data;
      }
    });
  }

  // 获取客户银行账户列表
  getBankList = custId => {
    const { dispatch } = this.props;
    const { bankList } = this.state;
    dispatch({
      type: 'singlemanage/getBankAccoList',
      payload: {
        custId,
      },
    }).then(response => {
      if (response.success && response.data && response.data.length) {
        const bankAccoList = [];
        response.data.map(item => {
          const temp = item;
          temp.bankId = this.matchDict(bankList, item.bankId);
          const bankInfo = `${item.bankId} ${item.bankAcco}`;
          const { bankAccoId } = item;
          bankAccoList.push({ bankAccoId, bankInfo });
        });
        this.setState({ bankAccoList });
      }
    });
  };

  // 获取公积金组合 （依据地区查公积金组合）
  getAreaData = (flag, value) => {
    const { dispatch, form } = this.props;
    const { PAY_FEES_WAY } = this.state;
    let payWay = '';
    PAY_FEES_WAY.forEach(item => {
      if (item.itemName === '单立户') {
        payWay = item.itemCode;
      }
    });
    this.setState({ selectedAreaId: value, payWay });
    if (flag === true) {
      form.resetFields(['plcyId']); //  重置上一次带出的公积金组合id
      dispatch({
        type: 'singlemanage/updateClearData',
        payload: {},
      });
    }
    dispatch({
      type: 'singlemanage/getAccuLsPkgName',
      payload: {
        payWay,
        areaId: value,
      },
    }).then(response => {
      if (response.success && response.data && response.data.length) {
        this.setState({ fundList: response.data });
      } else {
        this.setState({ fundList: [] });
      }
    });
  };

  // 匹配字典
  matchDict = (list, id) => {
    let dict = null;
    list.map(item => {
      if (Number(item.itemCode) === id) {
        dict = item.itemName;
      }
    });
    return dict;
  };

  // 选择是否开户完成
  isdoneFlag = e => {
    this.setState({ isdoneFlag: e });
  };

  // 选中支付方式
  selectPayWay = value => {
    this.setState({ payWay: value });
  };

  // 选中是否可突破上线
  selectExceedCeiling = value => {
    this.setState({ exceedCeilingFlag: value });
  };

  // 增加银行
  setModalShow = () => {
    this.setState({ updateModVisible: 'true' });
  };

  // 传给银行子组件的函数
  cancelModal = (modalClose, success) => {
    const { custId } = this.state;
    this.setState({ updateModVisible: modalClose });
    if (success) {
      this.getBankList(custId);
    }
  };

  // 弹出政策详情
  setPolicyModalShow = () => {
    this.setState({ policyVisible: 'true' });
  };

  // 传给政策子组件的函数
  cancelPolicyModal = modalClose => {
    this.setState({ policyVisible: modalClose });
  };

  // 选择公积金组合
  selectFundGroup = value => {
    const { fundList } = this.state;
    const fundGroup = fundList.filter(item => item.accuLsPkgId === value);
    this.setState({
      corpProp: fundGroup[0].corpProp,
      empProp: fundGroup[0].empProp,
      plcyId: value,
    });
  };

  // 取消
  cancel = () => {
    const { activeKey } = this.state;
    // eslint-disable-next-line no-unused-expressions
    activeKey
      ? router.push(`/customservicemanage/singleaccount/index?activeKey=${activeKey}`)
      : router.push(`/customservicemanage/singleaccount/index`);
  };

  // 提交数据
  submitAll = () => {
    const { dispatch, form } = this.props;
    const {
      custAccuAccoId,
      custId,
      payWay,
      exceedCeilingFlag,
      selectedAreaId,
      isdoneFlag,
      plcyId,
      corpProp,
      empProp,
      activeKey,
    } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ submitting: true });
        // eslint-disable-next-line no-param-reassign
        values = {
          custAccuAccoId, // 公积金账户id
          custId, // 客户名称id
          payWay, // 支付方式
          exceedCeilingFlag, // 是否可突破上限
          areaId: selectedAreaId, // 地区id
          custBankId: values.custBankId, // 银行账户id
          doneFlag: isdoneFlag, // 是否开户完成
          plcyId, // 公积金组合id
          remark: values.remark, // 备注
          accoName: values.accoName,
          uniCreditCode: values.uniCreditCode,
          orgName: values.orgName,
          accuOrg: values.accuOrg,
          accuComRatioVal: corpProp || null,
          accuPerRatioVal: empProp || null,
        };
        dispatch({
          type: 'singlemanage/auucUpdateSubmit',
          payload: values,
        }).then(response => {
          if (response.success) {
            message.success('修改成功', 2, () => {
              router.push(`/customservicemanage/singleaccount/index?activeKey=${activeKey}`);
            });
            this.setState({ submitting: false });
          } else {
            message.warning(`${response.message || '提交数据失败：服务器端错误'}`);
            this.setState({ submitting: false });
          }
        });
      }
    });
  };

  // 渲染函数
  render() {
    const {
      payWayList,
      fundList,
      updateModVisible,
      custId,
      bankAccoList,
      yesNoList,
      policyVisible,
      plcyId,
      accuOrIns,
      submitting,
    } = this.state;
    const {
      form: { getFieldDecorator },
      loading,
      singlemanage: { accuUpdateData },
    } = this.props;

    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin tip="Loading..." spinning={loading}>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>公积金户信息</span>}
              className={styles.card}
              bordered={false}
            >
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="客户名称">
                    {getFieldDecorator('custId', {
                      rules: [{ required: false, message: '请输入' }],
                      initialValue: accuUpdateData.custName,
                    })(<Input disabled />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="公积金账户名称">
                    {getFieldDecorator('accoName', {
                      rules: [{ required: true, pattern:/^(?!\.)[^\\/:*?"<>|]{1,255}$/,message: '文件名不能包含下列任何字符  \\  /  :  *   ?  "  <  >  |'}],
                      initialValue: accuUpdateData.accoName,
                    })(<Input placeholder="请输入" maxLength={100} />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="统一社会信用代码">
                    {getFieldDecorator('uniCreditCode', {
                      rules: [
                        {
                          required: false,
                          message: '长度为18位的数字与字母组合',
                          pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{18}$/,
                        },
                      ],
                      initialValue: accuUpdateData.uniCreditCode,
                    })(<Input placeholder="请输入" disabled />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="地区">
                    {getFieldDecorator('areaId', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: accuUpdateData.areaName,
                    })(
                      accuUpdateData.state === 2 || accuUpdateData.state === 3 ? (
                        <Input placeholder="请输入" disabled />
                      ) : (
                        <Area onSelect={value => this.getAreaData(true, value)} />
                      )
                    )}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="单位名称">
                    {getFieldDecorator('orgName', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: accuUpdateData.orgName,
                    })(
                      <Input
                        placeholder="请输入"
                        maxLength={100}
                        disabled={accuUpdateData.state === 2 || accuUpdateData.state === 3}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="支付方式">
                    {getFieldDecorator('payWay', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: accuUpdateData.payWayName,
                    })(
                      <Select
                        placeholder="请选择"
                        onChange={this.selectPayWay}
                        disabled={accuUpdateData.state === 2 || accuUpdateData.state === 3}
                      >
                        {payWayList.map(item => (
                          <Option key={item.itemCode}>{item.itemName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <FormItem label="是否可突破上限">
                    {getFieldDecorator('exceedCeilingFlag', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: accuUpdateData.exceedCeilingFlagName,
                    })(
                      <Select placeholder="请选择" onChange={this.selectExceedCeiling}>
                        {yesNoList.map(item => (
                          <Option key={item.itemCode}>{item.itemName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <Col span={22} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem label="银行账户信息">
                      {getFieldDecorator('custBankId', {
                        rules: [{ required: false, message: '请输入' }],
                        initialValue: accuUpdateData.custBankId,
                      })(
                        <Select placeholder="请选择">
                          {bankAccoList.map(item => (
                            <Option key={item.bankAccoId}>{item.bankInfo}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} offset={1} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem>
                      {custId ? (
                        <PlusCircleOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: '#40a9ff',
                            fontSize: '24px',
                          }}
                          onClick={this.setModalShow}
                        />
                      ) : (
                        <PlusCircleOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: 'rgb(206, 206, 206)',
                            fontSize: '24px',
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem
                    label={
                      <Tooltip
                        placement="right"
                        title="实际业务情况中该账户未开户完成，可以使用是否开户完成功能进行标记。后续开户完成时，进行修改取消标记即可。针对工伤险种，取消未开户完成标记时，需维护工伤比例信息。"
                      >
                        <span>是否开户完成</span>
                        <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
                      </Tooltip>
                    }
                  >
                    {getFieldDecorator('doneFlag', {
                      rules: [{ required: false, message: '请输入' }],
                      initialValue: accuUpdateData.doneFlagName,
                    })(
                      <Select
                        placeholder="请选择"
                        onChange={this.isdoneFlag}
                        disabled={
                          !!(
                            accuUpdateData &&
                            accuUpdateData.state !== 1 &&
                            accuUpdateData.doneFlag === 1
                          )
                        }
                      >
                        {yesNoList.map(item => (
                          <Option key={item.itemCode}>{item.itemName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                  <Col span={22} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem label="公积金组合">
                      {getFieldDecorator('plcyId', {
                        rules: [{ required: true, message: '请输入' }],
                        initialValue: accuUpdateData.plcyId,
                      })(
                        <Select
                          placeholder="请选择公积金组合"
                          onSelect={this.selectFundGroup}
                          disabled={accuUpdateData.state === 2 || accuUpdateData.state === 3}
                        >
                          {fundList.map(item => (
                            <Option key={item.accuLsPkgId}>{item.accuLsPkgName}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={1} offset={1} style={{ paddingLeft: 0, paddingRight: 0, float: 'left' }}>
                    <FormItem>
                      {plcyId ? (
                        <LinkOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: '#40a9ff',
                            fontSize: '24px',
                          }}
                          onClick={this.setPolicyModalShow}
                        />
                      ) : (
                        <LinkOutlined
                          style={{
                            width: '100%',
                            marginTop: 33,
                            color: 'rgb(206, 206, 206)',
                            fontSize: '24px',
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="所属公积金机构">
                    {getFieldDecorator('accuOrg', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: accuUpdateData.accuOrg,
                    })(<Input placeholder="请输入" maxLength={100} />)}
                  </FormItem>
                </Col>
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label="备注">
                    {getFieldDecorator('remark', {
                      initialValue: accuUpdateData.remark,
                    })(<Input placeholder="请输入" maxLength={200} />)}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            {updateModVisible === 'true' ? (
              <BankForm custId={custId} cancelModal={this.cancelModal} />
            ) : null}
            {policyVisible === 'true' ? (
              <Policy
                plcyId={plcyId}
                accuOrIns={accuOrIns}
                cancelPolicyModal={this.cancelPolicyModal}
              />
            ) : null}
            <FooterToolbar style={{ width: '100%' }}>
              <Button onClick={this.cancel} style={{ marginRight: 10 }}>
                取消
              </Button>
              <Button type="primary" onClick={this.submitAll} loading={submitting}>
                提交
              </Button>
            </FooterToolbar>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default AdvancedForm;
